package com.song.studylineserver.controller;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.log.Log;
import com.song.studylineserver.domain.LoginBody;
import com.song.studylineserver.domain.LoginUser;
import com.song.studylineserver.domain.Role;
import com.song.studylineserver.domain.User;
import com.song.studylineserver.service.MenuService;
import com.song.studylineserver.service.PostService;
import com.song.studylineserver.service.RoleService;
import com.song.studylineserver.service.UserService;
import com.song.studylineserver.util.IpUtils;
import com.song.studylineserver.util.Loggers;
import com.song.studylineserver.util.Result;
import com.song.studylineserver.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * 登录
 * @author songwentao
 *
 */
@RestController
@RequestMapping("/auth/")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    MenuService menuService;

    @Autowired
    PostService postService;

    @Autowired
    @Qualifier("StpInterfaceImpl")
    StpInterface stpService;


    //登录  ---- http://localhost:8081/user/doLogin
    @RequestMapping("login")
    public SaResult doLogin(@RequestBody LoginBody  form) {

        String name  =form.getUsername();
        String pwd  = form.getPassword();
        Loggers.info("获取到的用户名是"+name+"密码"+pwd);

        User temp =userService.getUserByUsername(name);
        if (StringUtils.isNull(temp))
        {
            return SaResult.error("没有这个用户，请重新操作！");
        }

        if(temp.getPassword().equals(SecureUtil.md5(pwd)))
        {
            StpUtil.login(temp.getUserId());
            LoginUser userinfo=new LoginUser();
            userinfo.setToken(StpUtil.getTokenValue());
            userinfo.setUserid(temp.getUserId());
            userinfo.setUsername(temp.getUserName());
            userinfo.setRoles(roleService.selectRolePermissionByUserId(temp.getUserId()));
            userinfo.setPermissions(menuService.selectMenuPermsByUserId(temp.getUserId()));
            userinfo.setLoginTime(System.currentTimeMillis());
            userinfo.setExpireTime(StpUtil.getTokenInfo().getTokenTimeout());
            Loggers.info("测试登录成功！");
            return new SaResult(200,"登录成功！",userinfo);
        }else{

            return SaResult.error("密码错误！请重新登录");
        }
    }

    // 查询登录状态  ---- http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public SaResult isLogin() {
        return SaResult.ok("是否登录：" + StpUtil.isLogin());
    }

    //通过token获取用户信息
    @RequestMapping("getUserInfo")
    public SaResult getUserInfo(String token)
    {
       String LoginId = (String) StpUtil.getLoginIdByToken(token);
       User temp = userService.getById(LoginId);

        return new SaResult(200,"获取成功!",temp);
    }


    // 查询 Token 信息  ---- http://localhost:8081/user/tokenInfo
    @RequestMapping("tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }

    // 测试注销  ---- http://localhost:8081/user/logout
    @RequestMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }


    @RequestMapping("register")
    public SaResult register(@RequestBody User register){

        Loggers.info(register.toString());

        //判断是否有重复用户
        if(userService.getUserByUsername(register.getUserName())!=null)
        {
            return SaResult.error("这个用户名已经被注册了,请重新选择");
        }else
        {
            User temp = register;

            //md5加密密码
            temp.setPassword(SecureUtil.md5(register.getPassword()));
            //设置创建时间
            temp.setCreateTime(DateTime.now());
            userService.saveOrUpdate(temp);
        }

        return SaResult.ok();
    }

    @RequestMapping("test")
    public Object getUser(String username){
        return userService.getUserByUsername(username);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = { "/", "/{userId}" })
    public Result getInfo(@PathVariable(value = "userId", required = false) String Id)
    {
        Long userId= Convert.toLong(Id);
        Loggers.info(userId.toString());
        userService.checkUserDataScope(userId);
        Result  data= Result.ok();
        List<Role> roles = roleService.selectRoleAll();
        data.put("roles", User.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        data.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            data.put("data", userService.selectUserById(userId));
            data.put("postIds", postService.selectPostListByUserId(userId));
            data.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return data;
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public Result getInfo()
    {
        Long userId = Convert.toLong(StpUtil.getLoginId());
        // 角色集合

        List<String> roles = stpService.getRoleList(userId,StpUtil.getLoginType());
        // 权限集合
        List<String> permissions = stpService.getPermissionList(userId,StpUtil.getLoginType());
        Result ajax = Result.ok();
        ajax.put("user", userService.selectUserById(userId));
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }
}
